<template>
  <div class="monthly-report">
    <div class="page-header">
      <h2>月度考勤报表</h2>
    </div>
    
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline size="default">
        <el-form-item label="姓名:">
          <el-input
            v-model="searchForm.employeeName"
            placeholder="请输入人员姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="班组名称:">
          <el-input
            v-model="searchForm.teamName"
            placeholder="请输入班组名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="月份:">
          <el-date-picker
            v-model="searchForm.yearMonth"
            type="month"
            placeholder="2025年07月"
            format="YYYY年MM月"
            value-format="YYYY-MM"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">确认检索</el-button>
        </el-form-item>
      </el-form>
      
      <div class="action-buttons">
        <el-button @click="handleReset">重置</el-button>
        <el-button @click="handleCalculate">重算</el-button>
        <el-button type="success" @click="handleExport">导出</el-button>
      </div>
    </div>
    
    <!-- 考勤报表 -->
    <div class="report-section">
      <div class="report-title">{{ currentMonthTitle }}考勤表</div>
      
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
        class="report-table"
      >
        <el-table-column prop="序号" label="序号" width="60" align="center" fixed="left" />
        <el-table-column prop="employeeName" label="姓名" width="80" fixed="left" />
        <el-table-column prop="employeeNumber" label="工号" width="80" fixed="left" />
        <el-table-column prop="teamName" label="班组名称" width="120" fixed="left" />
        
        <!-- 日期列说明 -->
        <el-table-column label="说明" width="80" align="center" fixed="left">
          <template #default>
            <div class="legend-cell">
              <div class="legend-item">班次</div>
              <div class="legend-item">时长</div>
              <div class="legend-item">状态</div>
              <div class="legend-item">实际</div>
            </div>
          </template>
        </el-table-column>
        
        <!-- 动态生成日期列 -->
        <el-table-column
          v-for="day in dayColumns"
          :key="day.date"
          :label="day.label"
          width="70"
          align="center"
          class-name="day-column"
        >
          <template #header>
            <div class="day-header">
              <div class="day-number">{{ day.day }}</div>
              <div class="weekday">{{ day.weekday }}</div>
            </div>
          </template>
          <template #default="{ row }">
            <div class="day-cell">
              <div class="cell-row shift-row">{{ row[`day${day.day}_shift`] || 'R' }}</div>
              <div class="cell-row hours-row">{{ row[`day${day.day}_hours`] || '0' }}</div>
              <div class="cell-row status-row" :class="getStatusClass(row[`day${day.day}_status`])">
                {{ getStatusShort(row[`day${day.day}_status`]) }}
              </div>
              <div class="cell-row actual-row">{{ row[`day${day.day}_attendance`] || '0' }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <span class="total-text">共{{ total }}条记录</span>
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 考勤明细弹窗 -->
    <el-dialog 
      v-model="detailVisible" 
      title="考勤明细" 
      width="1200px"
      :close-on-click-modal="false"
    >
      <div class="detail-content">
        <el-table 
          :data="detailData" 
          border 
          stripe
          style="width: 100%"
        >
          <el-table-column prop="teamName" label="班组名称" width="120" />
          <el-table-column prop="employeeName" label="姓名" width="100" />
          <el-table-column prop="whiteShiftDays" label="白班天数" width="100" align="center" />
          <el-table-column prop="nightShiftDays" label="夜班天数" width="100" align="center" />
          <el-table-column prop="scheduledHours" label="排班工时" width="100" align="center" />
          <el-table-column prop="actualHours" label="出勤工时" width="100" align="center" />
          <el-table-column prop="scheduledDays" label="排班天数" width="100" align="center" />
          <el-table-column prop="attendanceDays" label="出勤天数" width="100" align="center" />
          <el-table-column prop="absentDays" label="缺勤天数" width="100" align="center" />
          <el-table-column prop="lateCount" label="迟到早退次数" width="120" align="center" />
          <el-table-column prop="attendanceHoursRatio" label="出勤工时比率" width="120" align="center" />
          <el-table-column prop="attendanceDaysRatio" label="出勤天数比率" width="120" align="center" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getMonthlyAttendanceReports, exportMonthlyAttendanceReport } from '@/api/attendance'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const detailVisible = ref(false)
const detailData = ref([])
const currentRow = ref(null)

const searchForm = reactive({
  employeeName: '',
  teamName: '',
  yearMonth: dayjs().format('YYYY-MM')
})

const pagination = reactive({
  pageNum: 1,
  pageSize: 10
})

// 计算属性
const currentMonthTitle = computed(() => {
  return searchForm.yearMonth ? dayjs(searchForm.yearMonth).format('YYYY年MM月') : ''
})

const dayColumns = computed(() => {
  if (!searchForm.yearMonth) return []
  
  const date = dayjs(searchForm.yearMonth)
  const daysInMonth = date.daysInMonth()
  const columns = []
  
  for (let i = 1; i <= daysInMonth; i++) {
    const currentDate = date.date(i)
    columns.push({
      date: i,
      day: i,
      weekday: ['日', '一', '二', '三', '四', '五', '六'][currentDate.day()],
      label: `${i}`
    })
  }
  
  return columns
})

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      employeeName: searchForm.employeeName || undefined,
      teamName: searchForm.teamName || undefined,
      yearMonth: searchForm.yearMonth
    }
    
    const res = await getMonthlyAttendanceReports(params)
    const data = res.data
    
    // 处理后端返回的数据结构
    if (data.records && Array.isArray(data.records)) {
      // 如果返回的是 AttendanceMonthlyReportDTO 结构
      const processedData = []
      
      data.records.forEach((reportItem, index) => {
        if (reportItem.monthlySummary) {
          const summary = reportItem.monthlySummary
          const dailyRecords = reportItem.dailyRecords || []
          
          // 从dailyRecords中获取teamName（因为summary中没有teamName字段）
          const teamName = dailyRecords.length > 0 ? dailyRecords[0].teamName : '未知'
          
          const rowData = {
            employeeName: summary.employeeName,
            employeeNumber: summary.employeeNumber,
            teamName: teamName,
            序号: (pagination.pageNum - 1) * pagination.pageSize + index + 1,
            _originalReport: reportItem // 保存原始报表数据以供详情使用
          }
          
          // 处理每日记录
          const dailyMap = {}
          
          dailyRecords.forEach(daily => {
            if (daily.date) {
              const day = dayjs(daily.date).date()
              dailyMap[day] = daily
            }
          })
          
          // 为每一天填充数据
          for (let day = 1; day <= 31; day++) {
            const daily = dailyMap[day]
            if (daily) {
              rowData[`day${day}_shift`] = daily.shiftCode || 'R'
              rowData[`day${day}_hours`] = daily.scheduledDurationHours || '0'
              rowData[`day${day}_status`] = daily.attendanceStatus || '休息日'
              rowData[`day${day}_attendance`] = daily.actualWorkHours || '0'
              rowData[`day${day}_shift_2`] = daily.shiftCode || 'R'
              rowData[`day${day}_hours_2`] = daily.scheduledDurationHours || '0'
              rowData[`day${day}_normal`] = daily.isAbsent ? '缺勤' : (daily.isLate || daily.isEarlyLeave ? '异常' : '正常')
            } else {
              // 无数据日期
              rowData[`day${day}_shift`] = 'R'
              rowData[`day${day}_hours`] = '0'
              rowData[`day${day}_status`] = '休息日'
              rowData[`day${day}_attendance`] = '0'
              rowData[`day${day}_shift_2`] = 'R'
              rowData[`day${day}_hours_2`] = '0'
              rowData[`day${day}_normal`] = 'R'
            }
          }
          
          processedData.push(rowData)
        }
      })
      
      tableData.value = processedData
    } else {
      tableData.value = []
    }
    
    total.value = data.total || 0
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageNum = 1
  loadData()
}

const handleReset = () => {
  searchForm.employeeName = ''
  searchForm.teamName = ''
  searchForm.yearMonth = dayjs().format('YYYY-MM')
  pagination.pageNum = 1
  loadData()
}

const handleCalculate = () => {
  ElMessage.info('重算功能待实现')
}

const handleExport = async () => {
  try {
    const params = {
      employeeName: searchForm.employeeName || undefined,
      teamName: searchForm.teamName || undefined,
      yearMonth: searchForm.yearMonth
    }
    
    const res = await exportMonthlyAttendanceReport(params)
    
    // 创建下载链接
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `月度考勤报表_${searchForm.yearMonth}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
  }
}

const handleDetail = (row) => {
  currentRow.value = row
  
  // 从原始数据中获取月度汇总信息
  const monthlyReport = row._originalReport // 保存的原始报表数据
  if (monthlyReport && monthlyReport.monthlySummary) {
    const summary = monthlyReport.monthlySummary
    const detailRow = {
      teamName: row.teamName,
      employeeName: summary.employeeName,
      whiteShiftDays: summary.whiteShiftDays || 0,
      nightShiftDays: summary.nightShiftDays || 0,
      scheduledHours: summary.totalScheduledHours || 0,
      actualHours: summary.totalActualWorkHours || 0,
      scheduledDays: summary.totalScheduledDays || 0,
      attendanceDays: summary.actualAttendanceDays || 0,
      absentDays: summary.absentDays || 0,
      lateCount: (summary.lateCount || 0) + (summary.earlyLeaveCount || 0),
      attendanceHoursRatio: summary.attendanceHoursRatio ? `${summary.attendanceHoursRatio}%` : '0%',
      attendanceDaysRatio: summary.attendanceDaysRatio ? `${summary.attendanceDaysRatio}%` : '0%'
    }
    
    detailData.value = [detailRow]
  } else {
    ElMessage.warning('无法获取详细信息')
  }
  
  detailVisible.value = true
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNum = 1
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.pageNum = val
  loadData()
}

const getStatusClass = (status) => {
  if (status === '正常') return 'normal'
  if (status === '迟到') return 'late'
  if (status === '早退') return 'early'
  return 'rest'
}

const getNormalClass = (normal) => {
  if (normal === 'D') return 'day-shift'
  if (normal === 'N') return 'night-shift'
  return 'rest'
}

const getStatusShort = (status) => {
  if (!status || status === '休息日') return 'R'
  if (status === '正常') return '正'
  if (status === '迟到') return '迟'
  if (status === '早退') return '早'
  if (status === '缺勤') return '缺'
  return status.charAt(0)
}


// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.monthly-report {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      color: #333;
      margin: 0;
    }
  }
  
  .search-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    .action-buttons {
      display: flex;
      gap: 10px;
      
      .el-button {
        min-width: 80px;
      }
    }
  }
  
  .report-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
    .report-title {
      text-align: center;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
      color: #333;
    }
    
    .report-table {
      flex: 1;
      :deep(.day-column) {
        .cell {
          padding: 2px;
          overflow: hidden;
        }
      }
      
      .legend-cell {
        font-size: 11px;
        line-height: 1.4;
        
        .legend-item {
          padding: 2px 0;
          color: #666;
          border-bottom: 1px solid #f0f0f0;
          
          &:last-child {
            border-bottom: none;
          }
        }
      }
      
      .day-header {
        font-size: 12px;
        line-height: 1.3;
        padding: 2px 0;
        
        .day-number {
          font-weight: bold;
          color: #333;
        }
        
        .weekday {
          color: #666;
          font-size: 10px;
        }
      }
      
      .day-cell {
        font-size: 11px;
        line-height: 1.4;
        
        .cell-row {
          padding: 2px 0;
          border-bottom: 1px solid #f0f0f0;
          min-height: 16px;
          
          &:last-child {
            border-bottom: none;
          }
          
          &.shift-row {
            font-weight: 500;
            color: #333;
          }
          
          &.hours-row {
            color: #666;
            font-size: 10px;
          }
          
          &.status-row {
            font-weight: 500;
            
            &.normal {
              color: #52c41a;
            }
            
            &.late {
              color: #fa8c16;
            }
            
            &.early {
              color: #fa541c;
            }
            
            &.rest {
              color: #d9d9d9;
            }
          }
          
          &.actual-row {
            color: #666;
            font-size: 10px;
          }
        }
      }
    }
    
    .pagination-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
      
      .total-text {
        color: #666;
        font-size: 14px;
      }
    }
  }
}
</style>